﻿using Jinndev.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

namespace Jinndev {

    public static class CocosUtil {

        public static CocosPrefab ParsePrefabFile(string filePath) {
            string text = File.ReadAllText(filePath);
            JArray json = JArray.Parse(text);
            return ParsePrefab(json, Path.GetFileNameWithoutExtension(filePath));
        }

        public static CocosPrefab ParsePrefab(JArray json, string name) {
            CocosPrefab prefab = new CocosPrefab();

            Stack<CocosNode> nodeStack = new();

            foreach (JObject obj in json) {
                string type = JsonUtil.GetString(obj, "__type__");

                if (type == "cc.Prefab") {

                }
                else if (type == "cc.Node") { // 开始一个节点
                    var node = new CocosNode(obj);

                    if (prefab.rootNode == null) {
                        prefab.rootNode = node;
                    }
                    else {
                        nodeStack.Peek().AddChild(node);
                    }
                    nodeStack.Push(node);
                }
                else if (type == "cc.PrefabInfo") { // 结束一个节点
                    nodeStack.Pop();
                }
                else if (type.StartsWith("cc.") && !type.StartsWith("cc.Target")) {
                    // cc.TargetXxx 是嵌套的预设
                    var com = new CocosComponent(obj, type);
                    if (nodeStack.Count > 0) {
                        nodeStack.Peek().AddComponent(com);
                    }
                    else {
                        Debug.LogError($"组件没有节点, name: {name}, type: {type}, obj: {obj}");
                    }
                }
            }
            return prefab;
        }

        public static string GetResourceUuid(string jsonText) {
            jsonText = jsonText.Substring(jsonText.IndexOf("uuid\": \"") + 10);//第一个不是
            string uuid = CommonUtil.SubStringFromTo(jsonText, "uuid\": \"", "\",");
            return CommonUtil.SubStringTo(uuid, "@");
        }

    }

}
